package server;

import java.net.*;
import java.io.*;


public class Server {
	
	ServerSocket serverSocket = null; 	// NUll referens
	
	public Server()
	{		
		System.out.println("Starting server...");
		
		// Tests
		OpenSocket(35416);
		
//		try {		
//			serverSocket.close();
//		} catch(IOException ex) {
//			System.err.println("Clond not close socket at this time" + "\n" + ex );
//		}
//		
//		if( serverSocket.isClosed() )
//		{
//			System.out.println("Socket closed");
//		}
		
		// ToDo
		
		/**
		 * while (true){
		 * 		listen for new connections
		 * 			accept the new connection
		 * 				start a new created thread to comunicate with the client
		 * }  
		 */
		
		PrintWriter out = null;
		BufferedReader  in = null;
		
		// Wait for clients forever
		while( true )
		{
			Socket cs = null;
			try{
				// Blocking 
				cs = serverSocket.accept();
				out = new PrintWriter(cs.getOutputStream(), true);
				in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
				
				System.out.println("Connection established");
				
				String str;
				while( ( str = in.readLine() ) != null )
				{
					out.println("Message from client: " + str);
					System.out.println("Message echo: " + str);
				}
				
				out.close();
				in.close();
				cs.close();
				
			} catch(Exception ex) {
				System.err.println("Error: " + ex);
				System.exit(1);
			}
			System.out.println("Done");
			System.exit(0);
		}
	}
	
	private void OpenSocket(int portNumber)
	{
		// Skapa en instans av ServerSocket
		try{
			serverSocket = new ServerSocket(portNumber);	
			System.out.println("New Socket opened @ " + portNumber);
		} catch (IOException ex){
			System.err.println("Port busy: #" + portNumber + "\n" + ex);
			System.exit(1);
		}					
	}
	
}
